package control

import (
	"github.com/gin-gonic/gin"
	"gorm/utility"
	"net/http"
)

var path_list = []string{"/login", "/register"}


func in(target string, str_array []string) bool {
	for _, element := range str_array {
		if target == element {
			return true
		}
	}
	return false

}
func TokenValidate() gin.HandlerFunc {
	return func(c *gin.Context) {
		path:=c.Request.URL.Path

		b := in(path,path_list)
		if b{
			c.Next()
			return
		}
		authorization := c.Request.Header.Get("Authorization")
		if authorization == "" {
			c.JSON(http.StatusOK,gin.H{
				"code":401,
				"mes":"登录失效",
			})
			c.Abort()
			return
		}
		token, err := utility.ParseToken(authorization);
		if err != nil {
			c.JSON(http.StatusOK,gin.H{
				"code":401,
				"mes":err.Error(),
			})
			c.Abort()
			return
		}
		// 设置 example 变量
		c.Set("userId", token.UserId);
		c.Next()
	}
}





